package com.study.service.Impl;

import com.study.enums.ResultCodeEnum;
import com.study.exception.MyException;
import com.study.mapper.HeartbeatMapper;
import com.study.pojo.dto.Heartbeat;
import com.study.service.HeartbeatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class HeartbeatServiceImpl implements HeartbeatService {
    @Autowired
    private HeartbeatMapper heartbeatMapper;


    @Override
    public List<Heartbeat> queryAll(Integer loveId, Integer start, Integer num) {
        return heartbeatMapper.queryAll(loveId, start, num);
    }

    @Override
    public void insertHeart(Heartbeat heartbeat) {
        // 设置总心跳
        try {
            Heartbeat lastHeartbeat = getLastHeartbeat(heartbeat.getLoveId());
            // 2. 不是第一次添加，先查询最后一次添加记录计算新总值
            // 通过add_min（1加分 0减分）状态计算总值
            if ("1".equals(heartbeat.getAddMin())) {
                heartbeat.setTotalPoints(heartbeat.getScore() + lastHeartbeat.getTotalPoints());
            } else {
                heartbeat.setTotalPoints(lastHeartbeat.getTotalPoints() - heartbeat.getScore());
            }
            if (heartbeat.getExchangePoint() == null) {
                heartbeat.setExchangePoint("false");
            }
            heartbeatMapper.insertHeart(heartbeat);
        } catch (MyException e) { // 这里捕获getLastHeartbeat抛出的异常
            // 1. 第一次添加，查询不到上次添加，直接设置总值为分数
            heartbeat.setTotalPoints(heartbeat.getScore());
            heartbeat.setExchangePoint("false");
            heartbeatMapper.insertHeart(heartbeat);
        } catch (Exception e) {
            throw new MyException(ResultCodeEnum.SAVE_FAILURE);
        }
    }

    @Override
    public Heartbeat getLastHeartbeat(Integer loveId) {
        Heartbeat lastHeartbeat = heartbeatMapper.getLastHeartbeat(loveId);
        if (lastHeartbeat == null) {
            throw new MyException(ResultCodeEnum.QUERY_FAILURE);
        }

        return lastHeartbeat;
    }

    @Override
    public Heartbeat getHeartbeatById(Integer id) {
        Heartbeat heartbeatById = heartbeatMapper.getHeartbeatById(id);
        if (heartbeatById == null) {
            throw new MyException(ResultCodeEnum.QUERY_FAILURE);
        }
        return heartbeatById;
    }

    @Override
    public void updateHeartbeat(Heartbeat heartbeat) {
        if (heartbeatMapper.updateHeartbeat(heartbeat) == 0) {
            throw new MyException(ResultCodeEnum.CHANGE_FAILED);
        }
    }

    @Override
    public int getCount(Integer id) {
        return heartbeatMapper.getCount(id);
    }
}
